package cn.com.taiji.oospub.wechat.config;

import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.entity.MemberBaseInfo;
import cn.com.taiji.oospub.wechat.service.IMemberBaseInfoService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

import static cn.com.taiji.oospub.wechat.common.util.NetworkUtil.getIpAddress;


@Aspect
@Component
public class LoggerAspect {

    @Autowired
    private IMemberBaseInfoService memberBaseInfoService;


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //用户集合
    private ArrayList<MemberBaseInfo> userList;

    // 定义切点Pointcut
    @Pointcut("execution(* cn.com.taiji.oospub.wechat.controller..*.*(..))")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request;
        request = sra.getRequest();
//        MemberBaseInfo loginUser = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
//        if (loginUser == null) {
//            loginUser = memberBaseInfoService.getById("102837907511455db12a66322c51b0ba");
//            WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, loginUser);
//        }
        String url = request.getRequestURL().toString();
        System.out.println();
        System.out.println("请求开始===地址:" + url);
        System.out.println("请求开始===时间:" + LocalDateTime.now());
        String method = request.getMethod();
        String queryString = request.getQueryString();
        Object[] args = pjp.getArgs();
        //获取请求参数集合并进行遍历拼接
        if (args.length > 0) {
            if ("POST".equals(method)) {
                if (args.length > 2 && !StringUtils.hasText(queryString)) {
                    getKeyAndValue(args[0]);
                } else if (request.getParameterMap().size() > 0) {
                    printParams(request.getParameterMap());
                } else if (StringUtils.hasText(queryString)) {
                    for (String param : queryString.split("&")) {
                        System.out.println("接收到参数" + param.split("=")[0] + "的值为:" + param.split("=")[1]);
                    }
                }
            } else if ("GET".equals(method)) {
                if (StringUtils.hasText(queryString)) {
                    for (String param : queryString.split("&")) {
                        System.out.println("接收到参数" + param.split("=")[0] + "的值为:" + param.split("=")[1]);
                    }
                }
            }
        }
        String ipAddress = getIpAddress(request);
        WebUtils.setSessionAttribute(request, SessionNames.LOGIN_IP, ipAddress);
        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();
//        System.out.println("请求结束");
        return result;
    }

    private static void getKeyAndValue(Object obj) {
        // 得到类对象
        Class userCla = obj.getClass();
        /* 得到类中的所有属性集合 */
        Field[] fs = userCla.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            f.setAccessible(true); // 设置些属性是可以访问的
            Object val;
            try {
                val = f.get(obj);
                // 得到此属性的值
                if (val != null && !"serialVersionUID".equals(f.getName())) {
                    System.out.println("接收到参数" + f.getName() + "的值为:" + val);
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    private static void printParams(Map<String, String[]> obj) {
        for (String key : obj.keySet()) {
            System.out.println("接收到参数" + key + "的值为:" + Arrays.toString(obj.get(key)));
        }
    }
}
